<?php
/**
 * User: b179a9
 * Date: 10/4/11
 * Time: 7:06 PM
 */

namespace Managers;

class Items extends BaseManager
{

    const TIME_IN_CACHE = 1;

    protected $__table = '\Catalog\Items';
    protected $__rubricsTable = '\Catalog\ItemsRubrics';

    public function save(array $params)
    {

        $obj = array_key_exists('id', $params) && !empty($params['id']) ?
                $this->_em->find($this->__table, $params['id']) :
                new \Catalog\Items();

        if ($obj) {
            $obj->setContent($params['content']);
            $obj->setEmail($params['email']);
            $obj->setName($params['name']);
            $obj->setPhone($params['phone']);
            $obj->setUpdatedAt(new \DateTime());

            $rubric = $this->_em->getReference($this->__rubricsTable, $params['rubric']);

            $obj->setRubric($rubric);

            $subrubric = $this->_em->getRepository($this->__rubricsTable)->findOneBy(array('id' => $params['subrubric'],
                                                                                          'parent' => $params['rubric']));
            if (empty($rubric)) {
                throw new \Exception('Invalid subrubric.');
            }
            $obj->setSubrubric($subrubric);
            $this->_em->persist($obj);
            $this->_em->flush();
        }

        return $obj;
    }

    public function getByRubric($rubric_id, $limit, $start = 0)
    {
        $cacheName = sprintf('items_%s_%s_%s', $rubric_id, $limit, $start);
        $res = $this->_getCacheManager()->load($cacheName);

        if (!$res) {

            $res = $this->_em->createQueryBuilder()
                    ->select('i,s')
                    ->from($this->__table, 'i')
                    ->join('i.subrubric', 's')
                    ->andWhere('i.subrubric = :subrubric')
                    ->setParameter('subrubric', $rubric_id)
                    ->setMaxResults($limit)
                    ->setFirstResult($start)
                    ->orderBy('i.updatedAt', 'desc')
                    ->getQuery()
                    ->getArrayResult();

            $this->_getCacheManager()->save($res, $cacheName, array('items'), self::TIME_IN_CACHE);

        }
        return $res;

    }

    public function getCountByRubric($rubric_id)
    {
        $res = $this->_em->createQueryBuilder()
                ->select('count(i.id) as total')
                ->from($this->__table, 'i')
                ->where('i.subrubric = :subrubric')
                ->setParameter('subrubric', $rubric_id)
                ->getQuery()
                ->getArrayResult();
        return $res[0]['total'];
    }

    public function getByArray($params)
    {
        $qb = $this->_em->createQueryBuilder()
                ->select('i,r,s')
                ->from($this->__table, 'i')
                ->join('i.rubric', 'r')
                ->join('i.subrubric', 's');
        foreach ($params as $param) {
            $qb->orWhere('i.id = ' . $param['id']);
        }

        $res = $qb->getQuery()->getArrayResult();
        return $res;
    }

}
